﻿using System;
using System.Collections.Generic;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iPdf
{
    class PdfPageInformer
    {
        private PdfReader reader;
        private int numberOfPages;
        private iTextSharp.text.Rectangle[] pageSizeArray;

        public bool IsValid
        {
            get
            {
                return reader != null;
            }
        }

        public PdfPageInformer(string pdf)
        {
            try
            {
                reader = new PdfReader(new RandomAccessFileOrArray(pdf), null);
            }
            catch
            {
                reader = null;
            }

            Initialize();
        }

        public PdfPageInformer(PdfReader reader)
        {
            if (reader == null)
            {
                throw new Exception("Bad argument");
            }

            this.reader = reader;
            Initialize();
        }

        public int NumberOfPages
        {
            get
            {
                return numberOfPages;
            }
        }

        public Rectangle GetPageRectange(int pageNo)
        {
            return pageSizeArray[pageNo-1];
        }

        private void Initialize()
        {
            //cache the number of pages and the page sizes to speed up the query
            numberOfPages = reader.NumberOfPages;
            pageSizeArray = new iTextSharp.text.Rectangle[numberOfPages];
            for (int i = 1; i <= numberOfPages; ++i)
            {
                pageSizeArray[i - 1] = reader.GetPageSizeWithRotation(i);
            }

            reader.Close();
        }
    }
}
